<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // 检查是否有认证token
        $token = $request->bearerToken();
        
        if (!$token) {
            return response()->json([
                'success' => false,
                'message' => '未提供认证token'
            ], 401);
        }

        // 验证token并获取用户
        $user = Auth::guard('sanctum')->user();
        
        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => '无效的认证token'
            ], 401);
        }

        // 检查用户是否为管理员
        if (!$user->is_admin) {
            return response()->json([
                'success' => false,
                'message' => '权限不足，需要管理员权限'
            ], 403);
        }

        // 将用户信息添加到请求中
        $request->merge(['admin_user' => $user]);

        return $next($request);
    }
}
